var MessageHandler = function() {
}

MessageHandler.prototype = {
	messages : [],
	areNew : false,
	openEditor : function(per) {
		(new ContentLoader()).showPreloader();
		$('#wrapper').css({
			opacity : 0.4,
			'z-index' : 99999
		});
		$('#message-box').remove();
		var editorWindow = $('<div />', {
			id : 'message-box'
		});
		var close = $('<div />', {
			id : 'close-button'
		});
		var person = $('<div />', {
			id : 'receiver-span',
			text : 'Contact ' + per + ' by sending him a message'
		});
		$(close).attr('onclick', '(new MessageHandler()).closeEditor();');
		var inputBox = $('<textarea />', {
			id : 'message-box-input'
		});
		var sendMsg = $('<div id="message-box-send" class="button" onclick="(new MessageHandler()).send(\'' + per
				+ '\');"><span>Send Request!</span></div>');
		$(editorWindow).append($(close));
		$(editorWindow).append($(person));
		$(editorWindow).append($(inputBox));
		$(editorWindow).append($(sendMsg));
		$('#preloader').remove();
		$('#main-container').prepend($(editorWindow));
	},
	closeEditor : function(el) {
		$('#message-box').remove();
		$('#wrapper').animate({
			opacity : 0,
			'z-index' : 0
		});
	},
	send : function(to) {
		if ($('#message-box-input').val() == null || $('#message-box-input').val() == '')
			return;
		if (!$.cookie('uid')) {
			(new APP()).login();
			return;
		}
		var this_ = this;
		$.ajax({
			url : '/s/?action=send_message',
			data : 'to=' + to + '&msg=' + $('#message-box-input').val(),
			success : function(resp) {
				if (resp.success === true) {
					$('.sign-in').append('<em style=\'color:blue;font-size:13px;\'>Message successfully sent</em>');
					(new MessageHandler()).closeEditor();
					console.log('Your message successfully sent. ' + to + 'will answer you as soon as he can');
				} else
					console.log(resp.err);
			}
		});
	}
};

MessageHandler.prototype.onMessage = function(messages, areNew) {
	messages = messages || {};
	if (messages.length != 0) {
		window.messageHandler.messages = messages.msg;
		if (areNew) {
			var numberDiv = $('<div />', {
				text : messages.length,
				id : 'inbox-number'
			});
			window.messageHandler.areNew = true;
			$('.inbox-header-button').append($(numberDiv));
		} else {
			(new ContentLoader()).loadInbox();
		}
	}
}

MessageHandler.prototype.getOld = function() {
	var this_ = this;
	$.ajax({
		url : '/s/?action=get_all_msg',
		success : function(resp) {
			if (resp.success === true) {
				if (resp.inbox != null) {
					this_.onMessage(resp.inbox, false);
				}
			}
		}
	});
}

var messageHandler = new MessageHandler();